package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson2.JSON;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private BedServiceImpl bedService;
    @Autowired
    private ContractServiceImpl contractService;
    @Autowired
    private CheckInConfigServiceImpl checkInConfigService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCheckIn(CheckInApplyDto dto) {
        //判断老人是否入住
        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if(elder!=null&&elder.getStatus()==1){
            throw new RuntimeException("该老人已入住");
        }


        //更新床位状态
        bedService.lambdaUpdate()
                .set(Bed::getBedStatus, 1)
                .eq(Bed::getId, dto.getCheckInConfigDto().getBedId())
                .update();
        Bed bed = bedService.selectBedById(dto.getCheckInConfigDto().getBedId());
        if(bed==null){
            throw new RuntimeException("床位不存在");
        }
        //新增或更新老人
        Elder elder1 = new Elder();
        BeanUtil.copyProperties(dto.getCheckInElderDto(), elder1);
        elder1.setStatus(1);
        elder1.setBedId(dto.getCheckInConfigDto().getBedId());
        //select bed_number from bed where id = dto.getCheckInConfigDto().getBedId()
        elder1.setBedNumber(bed.getBedNumber());
        elder1.setBedId(bed.getId());

        elderService.saveOrUpdate(elder1);
        //新增签约办理
        Contract contract = new Contract();
        BeanUtil.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder1.getId());
        contract.setElderName(elder1.getName());
        contract.setContractName("签约办理");
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setSignDate(LocalDateTime.now());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contractService.insertContract(contract);
        //新增入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtil.copyProperties(dto.getCheckInConfigDto(),checkIn );
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        insertCheckIn(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(dto.getCheckInConfigDto(),checkInConfig );
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.insertCheckInConfig(checkInConfig);
    }

    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //查询入住信息
        CheckIn checkIn = selectCheckInById(id);

        //查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtil.copyProperties(elder,checkInElderVo);
//        checkInElderVo.setAge(LocalDate.now().getYear()-Integer.parseInt(elder.getIdCardNo().substring(6,14)));
        //41012218701010
        // 根据身份证号计算精确年龄
        String idCardNo = elder.getIdCardNo();
        if (idCardNo != null && idCardNo.length() >= 15) {
            try {
                String birthDateStr = "";
                if (idCardNo.length() == 18) {
                    // 18位身份证号
                    birthDateStr = idCardNo.substring(6, 14);
                    birthDateStr = birthDateStr.substring(0, 4) + "-" +
                            birthDateStr.substring(4, 6) + "-" +
                            birthDateStr.substring(6, 8);
                } else if (idCardNo.length() == 15) {
                    // 15位身份证号
                    birthDateStr = idCardNo.substring(6, 12);
                    birthDateStr = "19" + birthDateStr.substring(0, 2) + "-" +
                            birthDateStr.substring(2, 4) + "-" +
                            birthDateStr.substring(4, 6);
                }

                LocalDate birthDate = LocalDate.parse(birthDateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate currentDate = LocalDate.now();
                Period period = Period.between(birthDate, currentDate);

                // 设置年龄（以年为单位）
                checkInElderVo.setAge(period.getYears());
            } catch (Exception e) {
                // 如果解析失败，设置默认年龄为0
                checkInElderVo.setAge(0);
            }
        } else {
            // 如果身份证号无效，设置默认年龄为0
            checkInElderVo.setAge(0);
        }
        //查询家人信息
   List<ElderFamilyVo> list = new ArrayList<>();
   if(checkIn.getRemark()!=null){
       list= JSON.parseArray(checkIn.getRemark(),ElderFamilyVo.class);
   }
        //查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigService
                .lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id)
                .one();
   CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
   BeanUtil.copyProperties(checkInConfig,checkInConfigVo);
   checkInConfigVo.setStartDate(checkIn.getStartDate());
   checkInConfigVo.setEndDate(checkIn.getEndDate());
   checkInConfigVo.setBedNumber(elder.getBedNumber());
        //查询合同
    Contract contract = contractService
            .lambdaQuery()
            .eq(Contract::getElderId, elder.getId())
            .eq(Contract::getContractName, "签约办理")
            .one();
    CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
    checkInDetailVo.setCheckInElderVo(checkInElderVo);
    checkInDetailVo.setElderFamilyVoList(list);
    checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
    checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
